package com.app.newiptv.activity;

import com.app.newiptv.promote.UpgradeUtil;
import com.app.newiptv.utils.APPLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by wendal on 2017/11/11.
 */

public class DownLoadApp {
    public static File upgrade(String addr, String loadDir, UpgradeUtil.DownloadListener listener) throws Exception {
        URL url = new URL(addr);
        APPLog.printInfo(addr+"下载地址："+url);
        String path = url.getPath();
        int index = path.lastIndexOf("/") + 1;
        String fileName = path.substring(index);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(30 * 1000);
        InputStream in = conn.getInputStream();
        File loadFileDir = new File(loadDir);
        if (!loadFileDir.exists()) {
            loadFileDir.mkdirs();
        }
        File downloadFile = new File(loadFileDir,"sp"+fileName+".apk");
        APPLog.printInfo("downloadFile:"+ downloadFile.getAbsolutePath());
        FileOutputStream out = new FileOutputStream(downloadFile);
        byte[] buf = new byte[1024];
        int progress = 0;
        int contentLen = conn.getContentLength();
        int len = in.read(buf);
        while (len != -1) {
            progress += len;
            out.write(buf, 0, len);
            if (listener != null) {
                listener.onLoading(progress, contentLen);
            }
            len = in.read(buf);
        }
        if (listener != null) {
            if (progress == 0) {
                listener.onFailed();
            } else {
                listener.onLoaded(downloadFile);
            }
        }
        in.close();
        out.close();
        return downloadFile;
    }
}
